package ilbunilcho.lol.parser;

import ilbunilcho.lol.exception.ChampionNotFoundException;
import ilbunilcho.lol.exception.ServerUnavailableException;

import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.util.Iterator;

import org.apache.log4j.Logger;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

public class Champions {
	Logger L = Logger.getLogger(Champions.class);
	
	String baseUrl = null;
	String url = null;
	String[][] ret = null;
	
	public Champions(String baseUrl) {
		this.baseUrl = baseUrl;
		this.url = baseUrl + "/champions";
	}
	
	public void parse() throws ServerUnavailableException, ChampionNotFoundException {
		try {
			Document doc = Jsoup.connect(url).get();
			Element body = doc.body();
			
			Elements champion_list = body.select("div#list_view.champion_list > div");

			if(!champion_list.isEmpty()) {
				Iterator<Element> iter = champion_list.iterator();
				
				int cnt = 0;
				ret = new String[champion_list.size()][8];

				while(iter.hasNext()) {
					Element el = iter.next();
					
					ret[cnt][0] = el.className().trim().replaceAll("filter_tag_", "").replaceAll(" ", ",");//tag
					ret[cnt][1] = baseUrl + el.select("td.champion > a").attr("href");//link
					ret[cnt][2] = el.select("td.champion > a > img").attr("src");//image
					ret[cnt][3] = el.select("td.description > span > a").text();//name
					ret[cnt][4] = el.select("td.statistics > table > tbody > tr").get(0).getElementsByAttributeValueMatching("class", ".+").size() + "";//attack
					ret[cnt][5] = el.select("td.statistics > table > tbody > tr").get(1).getElementsByAttributeValueMatching("class", ".+").size() + "";//health
					ret[cnt][6] = el.select("td.statistics > table > tbody > tr").get(2).getElementsByAttributeValueMatching("class", ".+").size() + "";//difficulty
					ret[cnt][7] = el.select("td.statistics > table > tbody > tr").get(3).getElementsByAttributeValueMatching("class", ".+").size() + "";//spells

					cnt++;
				}
				
				for(String s : ret[0]) {
					L.debug("s + " + s);
				}
			}
			else {
				throw new ChampionNotFoundException();
			}
		}
		catch(IOException e) {
			throw new ServerUnavailableException();
		}
	}
	
	public String[][] getRotation() {
		return ret;
	}
	
	public static void main(String[] args) {
		PrintStream out = System.out;
		String baseUrl = "http://na.leagueoflegends.com/en";
		
		try {
			Champions champ = new Champions(baseUrl);
			champ.parse();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
